// pages/order/detail/detail.js
import {
  formatTime
} from '../../../utils/util'
import {
  editOrder,
  getOrder,
  payOrder,
} from '../../../api/order'

import {
  wxPay,
  buy,
} from '../../../api/pay'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    jsonKey: '',
    jsonVal: '',
    orderStatus: [],
    receiverId: '',
    addressDetail: {
      name: '',
      phone: '',
      address: '',
    },
    goods: [],
    message: '',
    messageVisible: '',
    orderId: '',
    status: '',
    expressFee: '',
    orderTotal: '',
    calendarVisible: false,
    weddingDate: '',
    expressVisible:false,
    postInfo: null,
    goodImg: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.orderId) {
      this.setData({
        orderId: options.orderId
      })
    }
    if (this.data.orderId) {
      this.getOrderInfo()
    } else {
      const eventChannel = this.getOpenerEventChannel()
      // 监听 acceptDataFromOpenerPage 事件，获取上一页面通过 eventChannel 传送到当前页面的数据
      eventChannel.on('acceptDataFromOpenerPage', (data) => {
        console.log(data)
        const {
          params,
          productId,
          spcesInfo,
          specCount,
          activeSpec,
          name,
          bannerList,
          price,
          // specCount,
        } = data
        const {
          jsonKey,
          jsonVal
        } = params
        //无规格商品
        console.log(spcesInfo, spcesInfo.length)

        if (!spcesInfo || spcesInfo.length === 0) {
          // console.log(spcesInfo , spcesInfo.length)
          this.setData({
            productId,
            orderTotal: price,
            goods: [{
              productName: name,
              specs: false,
              price,
              count: 1,
              pic: bannerList.length > 0 ? bannerList[0] : '',
              productId,
            }],
            jsonKey,
            jsonVal
          })

        } else {
          const obj = spcesInfo[activeSpec]
          const {
            title,
            price,
            stockCount
          } = obj
          this.setData({
            productId,
            orderTotal: +price * +specCount,
            goods: [{
              productName: name,
              specs: title,
              price: price,
              count: specCount,
              pic: bannerList.length > 0 ? bannerList[0] : '',

            }],
            jsonKey,
            jsonVal
          })
        }

      })


    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  getOrderInfo() {
    const {
      orderId
    } = this.data
    getOrder({
        orderId
      }).then(res => {
        console.log(res)
        if (res.data && res.data.orderInfo) {
          const {
            expressFee,
            items,
            orderId,
            orderTotal,
            message,
            status,
            postAddress,
            postPhone,
            postReceiver,
            weddingDate,
          } = res.data.orderInfo
          let goodImg = ''
          let postInfo = {
            postAddress,
            postPhone,
            postReceiver,
          }
 
          let goods = items.map(item => {
            let pic = item.productPic;
            let pics = pic.split(',')
            if (pics.length > 1) {
              pic = pics[0]
            }
            goodImg = pic

            return {
              ...item,
              pic
            }
          })


          this.setData({
            postInfo,
            goodImg,
            goods,
            expressFee,
            orderTotal,
            message,
            status,
            weddingDate,
            addressDetail: {
              name: postReceiver,
              phone: postPhone,
              address: postAddress,
            },
          })
        }
      })
      .catch(err => {

      })

  },
  closeMessageBox() {
    this.setData({
      messageVisible: false
    })
  },
  openMessageBox() {
    if (this.data.status != '0' && this.data.status != '' && this.data.status != '1') {
      // wx.showToast({
      //   title: '已发货物品请联系客服',
      //   icon:'none'
      // })
      return;
    }
    this.setData({
      messageVisible: true
    })
  },
  changeVal(e) {

    // console.log(e)
    this.setData({
      message: e.detail
    })
  },
  async subitOrder() {
    const {
      message,
      receiverId,
      orderId,
      addressDetail,
      weddingDate
    } = this.data
    let params = {
      message: String(message),
      receiverId: String(receiverId),
      orderId: String(orderId)
    }
    let hadData = addressDetail.address && addressDetail.name && addressDetail.phone



    if (!weddingDate) {
      wx.showToast({
        title: '请选择婚期',
        icon: 'none'
      })
      return;
    }
    params.weddingDate = weddingDate


    if (!params.receiverId && !hadData) {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return;
    }

    if (params.receiverId === '') {
      delete params.receiverId
    }
    if (!params.orderId) {
      const {
        jsonKey,
        jsonVal
      } = this.data
      const buyParams = {
        jsonKey
      };
      if (buyParams) {
        buyParams.jsonVal = jsonVal
      }
      const buyRes = await buy(
        buyParams
      )
      console.log(buyRes)
      if (buyRes.data && buyRes.data.order && buyRes.data.order.orderId) {
        params.orderId = buyRes.data.order.orderId
      }
      // wx.showToast({
      //   title: '数据错误',
      //   icon: 'none'
      // })
      // return;
    }



    if (!params.orderId) {
      wx.showToast({
        title: '订单id错误',
      })
      return;
    }
    this.setData({
      orderId: params.orderId
    })
    const edit = await editOrder(params)
    console.log('edit', edit)
    if (JSON.stringify(edit.data) === '{}') {
      console.log('success')
      // return 
    }

    const orderRes = await payOrder({
      orderId: String(params.orderId)
    })


    if (orderRes.data && orderRes.data.json) {
      try {
        const payRes = await wxPay(orderRes.data.json)
        // const {
        //   productId
        // } = this.data
        // const details = goods.map(item => {
        //   let name = item.specs ? item.specs.substr(0, 32) : item.productName.substr(0, 32)
        //   return {
        //     amount: item.count, // 商品数量（该字段必传）  Number || 数字字符串 不能小于或等于0
        //     category: '一般商品', // 改字段为商品类别（必传） String 最多支持 32 个字符
        //     id: item.productId, // 商品唯一id(必传)   String||Number
        //     name, // 商品名称（必传）  String  最多支持 32 个字符
        //   }
        // })
        // wx.aldPayOrder({
        //   price: orderTotal, // 订单总价（该字段必传）  Number || 数字字符串  
        //   details,
        // })
        wx.navigateTo({
          url: '/pages/order/order?status=1',
        })
      } catch (err) {
        wx.showToast({
          title: '取消付款',
          icon: 'none'
        })
        console.log(err)
        // setTimeout(() => {
        //   wx.navigateTo({
        //     url: '/pages/order/order?status=0',
        //   })
        // }, 500);
      }
      // console.log(payRes)

    } else {
      wx.showToast({
        title: '支付失败',
      })
      // wx.navigateTo({
      //   url: '/pages/order/order?status=0',
      // })
    }
  },
  toAddress() {
    if ((this.data.status != '0' && this.data.status != 0 && this.data.status != 1)) {
      wx.showToast({
        title: '已发货物品请联系客服',
        icon: 'none'
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/address/address',
      events: {
        setReceiverId: (obj) => {
          console.log(receiverId)
          const {
            receiverId,
            name,
            phone,
            address
          } = obj
          // addressDetail: {
          //   name: '',
          //   phone: '',
          //   address: '',
          //   receiverId,
          // },
          if (receiverId) {
            let addressDetail = {
              name,
              phone,
              address,
            }
            this.setData({
              receiverId,
              addressDetail,
            })
          }
        }
      }
    })
  },
  openCalendar() {
    if (this.data.status != '0' && this.data.status != '' && this.data.status != '1') {
      // wx.showToast({
      //   title: '已发货物品请联系客服',
      //   icon:'none'
      // })
      return;
    }
    this.setData({
      calendarVisible: true
    })
  },
  onCalendarClose() {
    this.setData({
      calendarVisible: false
    })
  },
  onCalendarConfirm(e) {
    const date = e.detail
    // console.log()
    const currentDate = formatTime(date, '-').substr(0, 10)
    this.setData({
      calendarVisible: false,
      weddingDate: currentDate
    })
  },
  async editOrder() {
    const {
      message,
      receiverId,
      orderId,
      addressDetail,
      weddingDate
    } = this.data
    let params = {
      message: String(message),
      receiverId: String(receiverId),
      orderId: String(orderId)
    }
    let hadData = addressDetail.address && addressDetail.name && addressDetail.phone

    if (!weddingDate) {
      wx.showToast({
        title: '请选择婚期',
        icon: 'none'
      })
      return;
    }
    params.weddingDate = weddingDate

    if (!params.receiverId && !hadData) {
      wx.showToast({
        title: '请选择地址',
        icon: 'none'
      })
      return;
    }

    if (params.receiverId === '') {
      delete params.receiverId
    }
    if (!params.orderId) {
      const {
        jsonKey,
        jsonVal
      } = this.data
      const buyParams = {
        jsonKey
      };
      if (buyParams) {
        buyParams.jsonVal = jsonVal
      }
      const buyRes = await buy(
        buyParams
      )
      console.log(buyRes)
      if (buyRes.data && buyRes.data.order && buyRes.data.order.orderId) {
        params.orderId = buyRes.data.order.orderId
      }
    }

    if (!params.orderId) {
      wx.showToast({
        title: '订单id错误',
        icon: 'none'
      })
      return;
    }
    this.setData({
      orderId: params.orderId
    })
    const edit = await editOrder(params)
    console.log('edit', edit)
    if (JSON.stringify(edit.data) === '{}') {
      console.log('success')
      wx.showToast({
        title: '修改成功',
        icon: 'none'
      })
      // return 
    }
  },

  seeExpress(e) {
    // const id  = this.data.orderId
    // wx.showToast({
    //   title: '查看物流信息' + id,
    //   icon: 'none'
    // })
    // let { postAddress ,postPhone, postReceiver,items } = this.data.order

    // let goodImg = items[0].productPic
    // console.log('goodImg',goodImg)
    this.setData({
      expressVisible: true,
      // currentOrderId: id,
      // goodImg:goodImg,
      // postInfo: {
      //   postAddress,
      //   postPhone,
      //   postReceiver,
      // }
    })

  },
  closeExpress(e) {
    this.setData({
      expressVisible: false,
      // currentOrderId: '',
      // postInfo: null,
    })
  },
})